package com.example.back.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.back.model.domain.User;
import com.example.back.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 功能：缓存预热任务
 * 作者：Zzl
 * 日期：2025/3/6 下午8:47
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    //    设置redis类型
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    //    重点用户
    private List<Long> mainUserList = Arrays.asList(1L);

    //    每天执行，预热推荐用户
    public void doCacheRecommendUser() {
        //        设置Redis锁名称："Zzl:precacheJob:cache:lock"
        RLock lock = redissonClient.getLock("Zzl:precacheJob:cache:lock");
        try {
            /**
             * 1.只能一个线程能获取到锁
             * lock.tryLock(等待时间, 持有时间, 时间类型);
             */
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("get Lock" + Thread.currentThread().getId());
//                将mainUserList里获取的用户遍历放到userId里
                for (Long userId : mainUserList) {
                    QueryWrapper<User> qw = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), qw);
//                    根据不同的userId动态的生成Redis的Key
                    String redisKey = String.format("Zzl:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
//                    写缓存
                    try {
                        valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            // 只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock" + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

}
